using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public struct RecoilChannel {

	[SerializeField] float resetFactor;
	[SerializeField] float dampenFactor;
	[SerializeField] float magnifier;
	[SerializeField] Vector2 clampRange;
	const float stepTime = 0.01f;
	public RecoilChannel(RecoilChannel from) {
		resetFactor=from.resetFactor;
		dampenFactor=from.dampenFactor;
		clampRange=from.clampRange;
		magnifier=from.magnifier;
		velocity=Vector2.zero;
		position=Vector2.zero;
		accumulatedTime=0;
	}

	public RecoilChannel(float resetFactor,float dampenFactor,float magnifier,Vector2 clampRange) {
		this.resetFactor=resetFactor;
		this.dampenFactor=dampenFactor;
		this.clampRange=clampRange;
		this.magnifier=magnifier;
		velocity=Vector2.zero;
		position=Vector2.zero;
		accumulatedTime=0;
	}

	public Vector2 velocity { get; private set; }
	public Vector2 position { get; private set; }

	public void ApplyRecoil(Vector2 deltaVelocity) {
		velocity+=deltaVelocity*magnifier;
	}

	public bool isInitial => velocity==Vector2.zero&&position==Vector2.zero;

	private void OnDrawGizmos() {

	}

	float accumulatedTime;
	public void Update(float deltaTime) {
		accumulatedTime+=deltaTime;
		while(accumulatedTime>stepTime) {
			UpdateCore();
			accumulatedTime-=stepTime;
		}
	}
	void UpdateCore(){
		if(isInitial) return;
		Vector2 force = Vector2.zero;
		if(position!=Vector2.zero) {
			Vector2 resetForce = -position.normalized;
			resetForce*=resetFactor*position.magnitude;
			force+=resetForce;
		}
		if(velocity!=Vector2.zero) {
			Vector2 dampenForce = -velocity.normalized;
			dampenForce*=dampenFactor*velocity.magnitude;
			force+=dampenForce;
		}

		position+=velocity*stepTime;
		velocity+=force*stepTime;

		Vector2 clampedPosition = position;
		clampedPosition.x=Mathf.Clamp(position.x,-Mathf.Abs(clampRange.x),Mathf.Abs(clampRange.x));
		clampedPosition.y=Mathf.Clamp(position.y,-Mathf.Abs(clampRange.y),Mathf.Abs(clampRange.y));
		position=clampedPosition;

		if(position.sqrMagnitude<0.001f&&velocity.sqrMagnitude<0.01f) {
			position=Vector2.zero;
			velocity=Vector2.zero;
		}
	}

}
